// ==========================================================================
// 所属模块：files
// 生成日期：2024-02-08 17:09:21 +0800 CST
// 生成路径: files/function.js
// 生成人：xScript_Engine
// 数据表：sys_files - 文件管理
// ==========================================================================

response.headers.add('X-Script-Version', 'uploads-1.0');
// DB_NAME = 'system_sql'


function add() {
	const params = payload.get().body.toObject();
	if (params.isCatalogue) {
		// 目录
		const sql = `INSERT INTO sys_files (file_id,file_name,privacy,is_folder,parent_id, proprietor_id, proprietor_name) VALUES (?, ?, ?, ?, ?, ?, ?);`;
		const res = SQL.exec('system_sql', sql, ex.suid().base58(), params.name, params.isPublic, params.isCatalogue, params.parentId, USER_INFO.user_id, USER_INFO.nickname);
		return res;
	}
}

function list() {
	const params = payload.get().query;
	if (params && params.isPublic == 0) {
		// 非公共文件
		const res = SQL.query('system_sql', `SELECT * FROM sys_files WHERE delete_time IS NULL AND privacy = 0 AND proprietor_id = ?`, params.userId);
		return JSON.stringify(res);
	}
	const res = SQL.query('system_sql', `SELECT * FROM sys_files WHERE delete_time IS NULL AND (privacy != 0 OR privacy IS NULL)`);
	return JSON.stringify(res);
}

function update() {
	const params = payload.get().body.toObject();
	const res = SQL.exec('system_sql', `UPDATE sys_files SET file_name = ? WHERE file_id = ?`, params.name, params.id);
	return res;
}

function del() {
	const fileId = payload.get().query.fileId;
	const res = SQL.exec('system_sql', `UPDATE sys_files SET delete_time = NOW()  WHERE file_id = ?`, fileId);
	return res;
}

function main() {
	// 验证用户权限
	'use api/user/acl/excerpt.js'

	switch (payload.get().method) {
		case 'GET':
			return list();
		case 'POST':
			return add();
		case 'PUT':
			return update();
		case 'DELETE':
			return del();
		default:
			response.status.notFound();
			return `404 page not found`;
	}
}
